package com.echo.im.engin.netty;


import com.echo.im.common.contant.RedisConstants;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 *
 * @author echo
 * @date 2024-08-18
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class IMServerGroup implements CommandLineRunner {

    public static volatile long serverId = 0;
    private final IMServer imServer;
    private final  RedisTemplate<String, Object> redisTemplate;

    @PostConstruct
    public void init() {
        // 初始化SERVER_ID
        String key = RedisConstants.IM_MAX_SERVER_ID;
        serverId = redisTemplate.opsForValue().increment(key, 1);
        log.info("初始化完毕 IMServerGroup serverId:{}", serverId);
    }

    /***
     * 判断服务器是否就绪
     *
     * @return
     **/

    public boolean isReady() {
        return imServer.isReady();
    }
    /**
     * 启动服务
     * @param args
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {

        // 启动服务
        imServer.start();
    }

    @PreDestroy
    public void destroy() {
        // 停止服务
        imServer.stop();
    }

}
